<template>
  <div>
    <div class="query-c">
      注册码有效期：
      <Input placeholder="请输入注册码有效期(最长30天)" v-model="expireIn" type="number" style="width: 240px" /> &nbsp;
      <Button @click="handleAdd()" style="width: 150px" type="primary">添加注册码</Button>
    </div>
    <br />
    <Table border :loading="loading" stripe :columns="columns1" :data="regCodes">
      <template slot-scope="{ row, index }" slot="action">
        <div>
          <Button @click="handleDelete(row, index)" :disabled="row.useTime !== '未使用'">删除</Button>
        </div>
      </template>
    </Table>
    <br />
    <!-- <Page :total="tasks.length" show-sizer show-elevator/> -->
  </div>
</template>

<script>
import { getAllRegCodes, addRegCode, deleteRegCode } from '../api/regCode'
export default {
  name: 'regCode',

  data () {
    return {
      regCodes: [],
      columns1: [
        {
          title: '注册码',
          key: '_id'
        },
        {
          title: '生成者',
          key: 'fromUsername'
        },
        {
          title: '过期时间',
          key: 'expireTime'
        },
        {
          title: '使用时间',
          key: 'useTime'
        },
        {
          title: 'Action',
          key: 'action',
          slot: 'action'
        }
      ],
      loading: false,
      expireIn: 7
    }
  },

  mounted () {
    this.fetchAllRegCodes()
  },

  methods: {
    async fetchAllRegCodes () {
      this.loading = true
      const res = await getAllRegCodes()
      this.regCodes = res.data.map(val => {
        if (new Date(val.useTime).getMilliseconds() === 0) {
          val.useTime = '未使用'
        }
        return val
      })
      this.loading = false
    },

    async handleDelete (row) {
      await deleteRegCode(row._id)
      this.$Notice.success({
        title: '删除成功!',
        desc: `${row._id} 删除成功!`,
        duration: 5
      })
      this.fetchAllRegCodes()
    },

    async handleAdd () {
      addRegCode(this.expireIn)
        .then(res => {
          this.$Notice.success({
            title: '添加成功!',
            duration: 5
          })
        })
        .catch(err => {
          this.$Notice.error({
            title: '添加失败',
            desc: err.response.data.message,
            duration: 5
          })
        })
        .finally(() => {
          this.expireIn = 7
          this.fetchAllRegCodes()
        })
    }
  }
}
</script>

<style scoped>
</style>
